﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Data;
using Keepo.Models;
using AlbumDesigner.Models.ViewModels;
using AlbumDesigner.Models.Types;
using Keepo.Helpers;
using System.IO;
using AlbumDesigner.Models.Enums;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    public class BackgroundImagesController : Controller
    {
        private AlbumContext db = new AlbumContext();

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult Index()
        {
            return View();
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult GetBackgroundImagesList(int categoryId, int Page = 1)
        {
            //get all the images of the specified Category
            var imagesList = db.BackgroundImages.Where(m => m.ImageCategoryId == categoryId && m.IsRemoved == false).ToList();

            var images = imagesList.Select(m => new BackgroundImageData(m)).ToList();

            //add the Paging settings to the images list
            int rowsPerPage = 12;
            int imagesCount = images.Count();
            int startIndex = (Page - 1) * rowsPerPage;
            int pagesCount = imagesCount / rowsPerPage;
            if (imagesCount % rowsPerPage > 0)
            {
                pagesCount++;
            }

            var imagesPages = images.Skip(startIndex).Take(rowsPerPage);

            return Json(new { Images = imagesPages, Pages = pagesCount });
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult GetCategoriesList()
        {
            //get all the categories
            var categoriesList = db.ImageCategories.ToList();

            var categories = categoriesList.Select(m => new ImageCategoryData(m)).ToList();

            return Json(categories);
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult CategoryForm(int? id)
        {
            //edit mode
            if (id != null)
            {
                var category = db.ImageCategories.Find(id);
                return PartialView(category);
            }
            //insert mode
            else
            {
                return PartialView();
            }
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult AddCategory(ImageCategory category)
        {
            //insert this category
            db.ImageCategories.Add(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה נוספה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult UpdateCategory(ImageCategory category)
        {
            //update this category
            var existingCategory = db.ImageCategories.Find(category.ImageCategoryId);
            existingCategory.Title = category.Title;
            existingCategory.TitleHebrew = category.TitleHebrew;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה עודכנה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult DeleteCategory(int id)
        {
            //find this category
            var category = new ImageCategoryData(db.ImageCategories.Find(id));

            //get all the categories as SelectList
            ViewBag.MoveToCategoryId = new SelectList(db.ImageCategories.Where(m => m.ImageCategoryId != id), "ImageCategoryId", "TitleHebrew");

            return PartialView(category);
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult DeleteCategory(int categoryId, int? moveToCategoryId)
        {
            //find this category
            var category = db.ImageCategories.Find(categoryId);

            //get all images of category
            var categoryImages = db.BackgroundImages.Where(m => m.ImageCategoryId == categoryId).ToList();

            var message = "הקטגוריה " + category.TitleHebrew + " נמחקה בהצלחה.";

            if (moveToCategoryId == null)
            {
                //delete all the Background Images of this category
                if (categoryImages.Count > 0)
                {
                    categoryImages.ForEach(m => db.BackgroundImages.Remove(m));
                    db.SaveChanges();
                }
            }
            else
            {
                //move all image of category to a different specified category
                categoryImages.ForEach(m => m.ImageCategoryId = moveToCategoryId);
                db.SaveChanges();

                message = "הקטגוריה " + category.TitleHebrew + " נמחקה והתמונות שבה הועברו לקטגוריה הנבחרת.";
            }

            //delete the category
            db.ImageCategories.Remove(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, message));
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult AddBackgroundImage(int categoryId)
        {
            //get all the categories as SelectList
            ViewBag.CategoryId = new SelectList(db.ImageCategories, "ImageCategoryId", "TitleHebrew", categoryId);

            return PartialView();
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult AddBackgroundImage(BackgroundImageData image)
        {
            //add the background image to the DB
            var backgroundImage = new BackgroundImage();
            backgroundImage.IsSingle = image.IsSingle;
            backgroundImage.IsRepeat = image.IsRepeat;
            backgroundImage.Title = image.Title;
            backgroundImage.URL = image.ThumbnailUrl;
            backgroundImage.ImageCategoryId = image.CategoryId;

            if (!String.IsNullOrEmpty(backgroundImage.URL))
            {
                ImageHelper.addDesignImage(backgroundImage);
            }

            return Json(new KeyValuePair<bool, string>(true, "תמונת הרקע נוספה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            if (file != null)
            {
                //generate file name for this image (guid string)
                var fileName = Guid.NewGuid().ToString().Substring(0, 6) + Path.GetExtension(file.FileName);

                //upload the image to the resources directory
                var directoryToSave = Server.MapPath("~/resources/backgrounds/" + fileName);
                file.SaveAs(directoryToSave);

                return Content("resources/backgrounds/" + fileName);
            }
            return Content("");
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult UpdateBackgroundImage(int id)
        {
            var backgroundImage = new BackgroundImageData(db.BackgroundImages.Find(id));

            return PartialView(backgroundImage);
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult UpdateBackgroundImage(BackgroundImageData image)
        {
            //find the specified image and update its details
            var existImage = db.BackgroundImages.Find(image.BackgroundImageId);

            existImage.IsSingle = image.IsSingle;
            existImage.IsRepeat = image.IsRepeat;
            existImage.Title = image.Title;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "תמונת הרקע עודכנה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult MoveImagesToCategory(string imagesIds, int categoryId)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the BackgroundImage and update its Category
                    var backgroundImage = db.BackgroundImages.Find(int.Parse(imageId));
                    backgroundImage.ImageCategoryId = categoryId;

                }
            }

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "תמונת הרקע הועברה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult DeleteBackgroundImage(string imagesIds)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the BackgroundImage and delete it
                    var backgroundImage = db.BackgroundImages.Find(int.Parse(imageId));
                    backgroundImage.IsRemoved = true;
                    db.SaveChanges();
                }
            }

            return Json(new KeyValuePair<bool, string>(true, "תמונת הרקע נמחקה בהצלחה."));
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult UploadMultiple(int categoryId)
        {
            //get all the categories as SelectList
            ViewBag.CategoryId = new SelectList(db.ImageCategories, "ImageCategoryId", "TitleHebrew", categoryId);

            return View();
        }

        [CheckPermission(section = "BackgroundImages")]
        [HttpPost]
        public ActionResult UploadMultiple(string Title, int CategoryId, bool IsSingle, bool IsRepeat, int FileIndex, int chunk = 0, int chunks = 1)
        {
            //check if there is a file uploaded
            if (Request.Files[0] != null)
            {
                HttpPostedFileBase Filedata = (Request.Files[0] as HttpPostedFileBase);

                //add the background image to the DB
                var backgroundImage = new BackgroundImage();
                backgroundImage.IsSingle = IsSingle;
                backgroundImage.IsRepeat = IsRepeat;
                if (!string.IsNullOrEmpty(Title))
                {
                    backgroundImage.Title = Title + " - " + FileIndex;
                }
                backgroundImage.ImageCategoryId = CategoryId;

                //find the relevant Directory that these files will be saved into
                var directoryToSave = Server.MapPath("~/resources/backgrounds");
                var url = "resources/backgrounds";

                if (chunk == 0)
                {
                    //generate file name for this image (guid string)
                    Session["FileName"] = Guid.NewGuid().ToString().Substring(0, 6) + Path.GetExtension(Filedata.FileName);
                }

                //save the file (the file could be sent in chunks, if it's big)
                using (var fs = new FileStream(directoryToSave + "\\" + Session["FileName"], chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[Filedata.InputStream.Length];
                    Filedata.InputStream.Read(buffer, 0, buffer.Length);

                    fs.Write(buffer, 0, buffer.Length);
                }

                backgroundImage.URL = url + "/" + Session["FileName"];

                //if this is the last chunk of the file
                if (chunk == chunks - 1)
                {
                    ImageHelper.addDesignImage(backgroundImage);
                    Session["FileName"] = "";
                }
            }

            return Json(true);
        }

        [CheckPermission(section = "BackgroundImages")]
        public ActionResult GenerateMissingThumbnails()
        {
            var backgrounds = db.BackgroundImages.ToList();

            foreach (var background in backgrounds)
            {
                if (!System.IO.File.Exists(Server.MapPath("~/" + background.ThumbnailUrl)) && !System.IO.File.Exists(Server.MapPath("~/" + background.LowResUrl)))
                {
                    background.ThumbnailUrl = "";
                    background.LowResUrl = "";
                    ImageHelper.CreateThumbnailAndLowRes(background);
                    db.SaveChanges();
                }
            }

            return Content("success");
        }

        // Flex
        public ActionResult GetBackgroundCategories()
        {
            var categories = db.ImageCategories.Select(m => new
            {
                key = m.ImageCategoryId,
                english = m.Title,
                hebrew = m.TitleHebrew
            });

            return Json(categories.ToArray(), JsonRequestBehavior.AllowGet);
        }

        // Flex
        [HttpPost]
        public ActionResult GetBackgroundImagesByCategoryId(int categoryId)
        {
            var images = db.BackgroundImages.Where(m => m.ImageCategoryId == categoryId && m.IsRemoved == false);
            return Json(images.ToArray().Select(m => m.export()).ToArray());
        }
    }
}
